<template>
  <div class="app-container">
    <el-form :inline="true" v-show="showSearch" ref="NameForm" :model="queryParams" class="demo-form-inline">
      <el-form-item label="品牌名称">
        <el-input v-model="queryParams.name" placeholder="请输入品牌名称" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="getList">搜索</el-button>
        <el-button :icon="Refresh" @click="resetName">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row>
      <el-button type="primary" :icon="Plus" plain @click="addBrand">新增</el-button>
      <el-button type="success" :disabled="showEdit" @click="changeBrand(form.id)" :icon="Edit" plain>修改</el-button>
      <el-button type="danger" :disabled="showDelete" @click="deleteBrand('')" :icon="Delete" plain>删除</el-button>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="brandList" style="width: 100%"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column prop="name" label="品牌名称" width="200"/>
      <el-table-column prop="logo" label="品牌图标" #default="scope">
        <img :src="scope.row.logo" width="50"/>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" #default="scope">

        <el-button link type="primary" icon="Edit" @click="changeBrand(scope.row.id)">修改</el-button>
        <el-button link type="primary" icon="Delete" @click="deleteBrand(scope.row.id)">删除</el-button>

      </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
                   :page-sizes="[10, 20, 30, 40]" :background="background"
                   layout="->,total, sizes, prev, pager, next, jumper"
                   :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>

    <el-dialog v-model="open" :title="title" width="500">
      <el-form :model="form" :rules="rules" ref="formId">
        <el-form-item label="品牌名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入品牌名称" clearable/>
        </el-form-item>
        <el-form-item label="品牌图标" prop="logo">
          <el-upload class="avatar-uploader" :action="imgUpload.url" :headers="imgUpload.headers"
                     :show-file-list="false" :on-success="handleAvatarSuccess">
            <img v-if="form.logo" :src="form.logo" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">
            确定
          </el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {getCurrentInstance, onMounted, reactive, ref, toRefs} from "vue";
import {Delete, Edit, Search, Refresh, Plus} from '@element-plus/icons-vue'
import {
  findBrandPageList,
  addBrandInfo,
  findBrandDetailInfoById,
  updateBrandInfo,
  deleteBrandById
} from "@/api/product/brand"
import {getToken} from "@/utils/auth.js";
import {ElMessage, ElMessageBox} from "element-plus";

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: '',
  },
  form: {},
  imgUpload: {
    headers: {
      Authorization: "Bearer " + getToken()
    },
    // 图片上传的方法地址:
    url: import.meta.env.VITE_APP_BASE_API + "/file/upload"
  }

})
let {queryParams, form, imgUpload} = toRefs(data)
let showSearch=ref(true)
const brandList = ref([])
const total = ref(0)
const background = ref(true)
const loading = ref(true)
const open = ref(false)
const title = ref("添加品牌")

function getList() {
  loading.value = true
  findBrandPageList(queryParams.value).then(res => {
    brandList.value = res.rows
    total.value = res.total
    loading.value = false
  })
}

onMounted(() => {
  getList()
})
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}
let {proxy} = getCurrentInstance();
const resetName = () => {
  queryParams.value.pageNum = 1,
      queryParams.value.pageSize = 10,
      queryParams.value.name = ''
  getList()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    logo: null,
  };
  proxy.resetForm("formId")
}

//上传图片
function handleAvatarSuccess(response, uploadFile) {
  form.value.logo = response.data.url
}

function addBrand() {
  reset()
  open.value = true
  title.value = "添加品牌"
}

//取消新增
function cancel() {
  open.value = false;
  reset();
}

function submitForm() {
  proxy.$refs['formId'].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateBrandInfo(form.value).then((res) => {
          if (res.code == 200) {
            ElMessage.success("修改成功！")
            open.value = false
            getList()
          } else {
            ElMessage.error("修改失败！")
          }
        })
      } else {
        addBrandInfo(form.value).then(res => {
          if (res.code == 200) {
            ElMessage.success("新增成功！")
            open.value = false
            getList()
          } else {
            ElMessage.error("新增失败！")
          }
        })
      }
    }
  })
}

//修改功能
function changeBrand(id) {
  reset()
  //修改之前回显
  findBrandDetailInfoById(id).then(res => {
    form.value = res.data
    form.value.id = id
    open.value = true
    title.value = "修改品牌信息"
  })
}

//删除
function deleteBrand(id) {
  const _ids = id || ids.value
  ElMessageBox.confirm(
      '你确认删除' + _ids + '号的品牌信息吗？',
      '删除品牌',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        return deleteBrandById(_ids)
      })
      .then(res => {
        if (res.code == 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getList()
        } else {
          ElMessage({
            type: 'error',
            message: '删除失败',
          })
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
        getList()
      })
}

let ids = ref([])
let showDelete = ref(true)
let showEdit = ref(true)

//批量操作
function handleSelectionChange(val) {
  ids.value = val.map(item => item.id)
  form.value.id = ids.value[0];
  showEdit.value = val.length != 1
  showDelete.value = !val.length
}

//表单校验规则
const rules = reactive({
  name: [{required: true, message: "品牌名称不能为空", trigger: "blur"}],
  logo: [{required: true, message: "品牌LOGO不能为空", trigger: "blur"}],
})
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>